import React, { useEffect } from 'react';
import { useSetState } from 'ahooks';
import { connect } from 'umi';
import { TRDefault } from '@/components/index.js';
import { PageLoading } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import { queryProvinceList, getWechatOfficialArticle } from './service';
import styles from './index.less';
import moment from 'moment';
import { DatePicker, Select, Button, Input, Table, Spin } from 'antd';
import { message } from 'antd';
import getImging from '@/assets/img/getImging.png';
import TjTable from '@/pages/ETrade/components/TjTable';

const { Column } = Table;
const { Option } = Select;
const { RangePicker } = DatePicker;
let defaultState = {
  dateList: [],
  markets: ['全部信息来源'],
  keyWords: '',
  dateMoment: [],
};
const TradingCenterArticleList = (props) => {
  const [state, setState] = useSetState({ ...defaultState });
  const [data, setData] = useSetState({
    marketList: [],
    articleList: [],
    article: '',
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 40,
    spinLoding: true,
    error: '',
  });
  const { hasMore, spinLoding, loading, error } = data;

  useEffect(() => {
    feach();
  }, []);

  const feach = async () => {
    setData({ spinLoding: true });
    const res = await queryProvinceList();
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (res.data.length > 0) {
        setData({ marketList: res.data });
        handleSearch();
      }
    } else {
      message.error('查询交易中心失败');
      setData({ error: res?.message || '系统异常' });
    }
    setData({ spinLoding: false });
  };

  const onChange = (value, dateString) => {
    setState({
      dateMoment: value,
      dateList: dateString,
    });
  };

  const getFileUrl = (attachmentPath) => {
    let signatureConf = {
      expires: 3600,
    };
    const url = new OSS({
      region: 'oss-cn-beijing',
      accessKeyId: 'LTAI4G7w6tvFNPQ4q2hcHcD6',
      accessKeySecret: 'ZgALLEnmeqjjcTxlJnDEKKfJ6R5GUy',
      bucket: 'tianrun',
    }).signatureUrl(attachmentPath, signatureConf);
    return Promise.resolve(url);
  };

  const handleSearch = async (type = null) => {
    setData({ loading: true, error: '' });
    if (type === 'search') {
      data.page = 1;
      data.articleList = [];
      setData({
        page: 1,
        articleList: [],
        hasMore: true,
        article: null,
      });
    }
    let params = {
      current: data.page,
      endDate: '',
      provinceTitles: [],
      size: data.pageSize,
      startDate: '',
    };

    if (type !== 'reset') {
      params.keyWord = state.keyWords;
      if (state.markets.length > 0 && !state.markets.includes('全部信息来源')) {
        params.provinceTitles = state.markets;
      }
      if (!!state.dateList && state.dateList.length > 1) {
        params.startDate = moment(state.dateList[0]).format('YYYY-MM-DD');
        params.endDate = moment(state.dateList[1]).format('YYYY-MM-DD');
      }
    } else {
      setState({
        ...defaultState,
      });
    }
    const res = await getWechatOfficialArticle(params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const { records, size } = res.data;
      if (records?.length < size) {
        setData({
          hasMore: false,
        }); // 数据已全部加载完毕
      } else {
        setData({
          page: data.page + 1,
        });
      }
      let articleList = records.map((item, index) => {
        return { ...item, index };
      });
      setData({
        articleList: [...data.articleList, ...articleList],
        loading: false,
      });
    } else {
      message.error('查询失败');
      setData({ error: res?.message || '系统异常' });
    }
    setData({ loading: false });
  };

  const filterList = async (value) => {
    let list = value;
    if (value.length > 1 && value.includes('全部信息来源')) {
      list = value.filter((item) => {
        return item != '全部信息来源';
      });
    } else if (value.length == 0) {
      list = ['全部信息来源'];
    }
    setState({ markets: list });
  };

  const setDetail = async (record) => {
    let img_url = '';
    if (!!record.imageUrl && record.imageUrl !== '404') {
      img_url = `http://101.35.7.118:8081/annex/annex/downLoadFile/${record.imageUrl}`;
      // img_url = await getFileUrl(record.imageUrl);
    } else if (record.imageUrl === '404') {
      img_url = '404';
    }
    setData({ article: { ...record, img_url } });
  };

  // 监听滚动事件
  const handleScroll = (e) => {
    const { scrollTop, clientHeight, scrollHeight } = e.target;
    if (scrollTop + clientHeight >= scrollHeight && hasMore && !loading) {
      handleSearch();
    }
  };

  const main = () => {
    return (
      <div className={styles.box}>
        <div className={styles.content}>
          <div className={styles.title}>文章列表</div>
          <div onScroll={handleScroll} style={{ overflow: 'auto' }}>
            <TjTable
              dataSource={data.articleList}
              primaryKey="dataId"
              columns={[
                { code: 'provinceCollectionTitle', title: '信息来源', width: 140 },
                { code: 'articleTime', title: '发布时间', width: 100 },
                { code: 'articleTitle', title: '文章标题' },
                {
                  code: 'opt',
                  title: '操作',
                  width: 88,
                  align: 'center',
                  render: (text, record) => {
                    return (
                      <div className={styles.flex_a}>
                        <a onClick={() => setDetail(record)}>查看</a>
                        <a target="blank" href={record.articleUrl}>
                          详情
                        </a>
                      </div>
                    );
                  },
                },
              ]}
            />
          </div>
        </div>
        <div className={styles.content}>
          <div className={styles.title}>查看文章</div>
          {!!data.article ? (
            <div>
              <div className={styles.articleTitle}>{data.article.articleTitle}</div>
              <div className={styles.titleInfo}>
                信息来源<span>{data.article.provinceCollectionTitle}</span>发布时间
                <span>{moment(data.article.articleTime).format('YYYYMMDD HHmmss')}</span>
              </div>
            </div>
          ) : (
            <></>
          )}
          {!!data.article && (
            <div className={styles.content_imgBox}>
              {data?.article?.img_url === '404' ? (
                <span>当前文章已失效</span>
              ) : !!data?.article?.img_url ? (
                <img src={data?.article?.img_url} alt="" />
              ) : (
                <img src={getImging} alt="" />
              )}
            </div>
          )}
        </div>
      </div>
    );
  };

  if (spinLoding) return <PageLoading />;
  if (!data.marketList.length) return <TRDefault type="lock" />;
  if (error) return <TRDefault type="error" message={error} />;
  return (
    <div className={styles.container}>
      <div className={styles.head}>
        <Select
          className={styles.provinceSelect}
          value={state.markets}
          placeholder=""
          mode="multiple"
          allowClear
          maxTagCount="responsive"
          onChange={filterList}
        >
          {data.marketList.map((t) => {
            return (
              <Option value={t?.item} key={t?.item}>
                {t.item}
              </Option>
            );
          })}
        </Select>
        <RangePicker
          className={styles.datePicker}
          format={'YYYYMMDD'}
          allowClear={false}
          value={state.dateMoment}
          separator={'-'}
          onChange={onChange}
        />
        <Input
          className={styles.wordInput}
          placeholder="请输入关键字"
          value={state.keyWords}
          onChange={(e) => {
            setState({
              keyWords: e.target.value,
            });
          }}
        />
        <Button
          className={styles.queryBtn}
          type="primary"
          onClick={() => {
            handleSearch('search');
          }}
        >
          查询
        </Button>
        <Button
          className={styles.reset}
          onClick={() => {
            handleSearch('reset');
          }}
        >
          重置
        </Button>
      </div>
      {main()}
    </div>
  );
};

export default connect(({ global }) => ({
  buttonPermissions: global.configure.buttonPermissions,
}))(TradingCenterArticleList);
